//
//  LXOAuthViewController.swift
//  weibo
//
//  Created by 罗心 on 16/6/25.
//  Copyright © 2016年 罗心. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class LXOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    // MARK: - 监听事件
    @objc private func cancelClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillClick(){
        let jsString = "document.getElementById('userId').value='',document.getElementById('passwd').value=''"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXOAuthViewController.cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(LXOAuthViewController.autoFillClick))
        navigationItem.title = "OAuth登录"
    }
    
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
    }
    
    //MARK: 懒加载webview
    private lazy var webView: UIWebView = {
        let view = UIWebView()
        view.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        let request = NSURLRequest(URL:url)
        view.loadRequest(request)
       return view
    }()

}


extension LXOAuthViewController: UIWebViewDelegate {
    // 开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString

        if let u = urlString where u.hasPrefix(REDIRECT_URI) {

            let query = request.URL?.query
            // 可选值判断
            if let q = query {
                let code = q.substringFromIndex("code=".endIndex)
                loadUserAccount(code)
                return false
            }
        }
        
        return true
    }
}

extension LXOAuthViewController {
    func loadUserAccount(code: String){
        
        LXNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) -> () in
            guard let res = response as? [String: AnyObject] else {
                return
            }
            // 字典转模型
            let userAccount = LXUserAccount(dict: res)
            self.loadUserInfo(userAccount)
        }) { (error) -> () in
            print(error)
        }
        
    }
    
    func loadUserInfo(userAccount: LXUserAccount){
        LXNetworkTools.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in

            guard let res = response as? [String: AnyObject] else {
                return
            }
            
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            // 归档保存数据
            LXUserAccountTools.sharedTools.saveUserAccount(userAccount)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in

                SVProgressHUD.dismiss()
                //  切换跟控制器
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNoti, object: nil)
            })
            
            
        }) { (error) -> () in
            print("失败\(error)")
        }
    }
}

